const Router = require("koa-router");
const { Address } = require("@models/address");
const { Auth } = require("@middlewares/auth");
const { sequelize } = require("@core/db");
const { where } = require("sequelize");

const router = new Router({
  prefix: "/v1/user/address",
});

// 添加用户地址
router.post("/add", new Auth().m, async (ctx, next) => {
  const { is_default, ...res } = ctx.request.body;
  if (is_default) {
    const where = {
      uid: ctx.auth.uid,
      is_default: true,
    };
    await Address.update(
      {
        is_default: 0,
      },
      {
        where,
      }
    );
  }

  const address = await Address.create({
    ...res,
    is_default,
    uid: ctx.auth.uid,
  });

  if (!address) {
    throw new global.errs.AuthFailed("地址添加失败");
  }
  ctx.body = {
    code: 200,
    msg: "添加成功",
  };
});

// 编辑用户地址
router.post("/update", new Auth().m, async (ctx, next) => {
  const { address_id } = ctx.request.body;

  const where = {
    uid: ctx.auth.uid,
    is_default: true,
  };
  await Address.update(
    {
      is_default: 0,
    },
    {
      where,
    }
  );

  const address = await Address.update(
    {
      is_default: true,
      uid: ctx.auth.uid,
    },
    { where: { address_id } }
  );

  if (!address) {
    throw new global.errs.AuthFailed("设置失败");
  }
  ctx.body = {
    code: 200,
    msg: "设置成功",
  };
});
// 删除用户地址
router.post("/delete", new Auth().m, async (ctx, next) => {
  const { address_id } = ctx.request.body;
  const where = {
    address_id,
  };
  const address = await Address.destroy({
    where,
    force: true,
  });

  if (address == 0) {
    throw new global.errs.AuthFailed("删除失败");
  }
  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

// 用户地址列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = {
    uid: ctx.auth.uid,
  };
  const { count: total, rows } = await Address.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [
      // 首先按照 address 字段进行排序，'默认地址' 排在最前面
      ["is_default", "desc"],
      // 如果 address 相同，则按照 created_at 字段进行升序排序
      ["created_at", "ASC"],
    ],
    raw: true,
  });
  if (!rows) {
    throw new global.errs.AuthFailed("获取失败");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

module.exports = router;
